<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="服务项目名" prop="serviceItemId">
        <el-select v-model="queryParams.serviceItemId" placeholder="请选择服务项目名" style="width: 100%;">
          <el-option v-for="item in serviceItems" :key="item.id" :label="item.serviceName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['service:detail:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
          v-hasPermi="['service:detail:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['service:detail:remove']">删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 服务详情列表 -->
    <el-table v-loading="loading" :data="detailList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" type="index" />
      <el-table-column label="服务项目名" align="center" prop="serviceItemName" />
      <el-table-column label="服务选项" align="center" prop="serviceOptions">
        <template slot-scope="scope">
          <div>
            <el-tag v-for="(option, index) in parseJson(scope.row.serviceOptions)" :key="index"
              style="margin-right: 5px;">
              {{ option }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="服务特点" align="center" prop="serviceFeatures">
        <template slot-scope="scope">
          <div>
            <el-tag v-for="(feature, index) in parseJson(scope.row.serviceFeatures)" :key="index"
              style="margin-right: 5px;">
              {{ feature }}
            </el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="故障类型" align="center" prop="faultTypes">
        <template slot-scope="scope">
          <div>
            <el-tag v-for="(fault, index) in parseJson(scope.row.faultTypes)" :key="index" style="margin-right: 5px;">
              {{ fault }}
            </el-tag>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="服务轮播图路径" align="center" prop="serviceCarouselImages" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.serviceCarouselImages" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="服务详情图路径" align="center" prop="serviceDetailImage" width="100">
        <template slot-scope="scope">
          <image-preview :src="scope.row.serviceDetailImage" :width="50" :height="50" />
        </template>
      </el-table-column>
      <el-table-column label="上门费用" align="center" prop="visitFee" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['service:detail:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['service:detail:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改服务详情对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="96px">
        <el-form-item label="服务项目名" prop="serviceItemId">
          <el-select v-model="form.serviceItemId" placeholder="请选择服务项目名" style="width: 80%;">
            <el-option v-for="item in serviceItems" :key="item.id" :label="item.serviceName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="服务选项" prop="serviceOptions">
          <el-input v-model="form.serviceOptions" placeholder="请输入服务选项，多个值请用逗号分隔" />
        </el-form-item>
        <el-form-item label="服务特点" prop="serviceFeatures">
          <el-input v-model="form.serviceFeatures" placeholder="请输入服务特点，多个值请用逗号分隔" />
        </el-form-item>
        <el-form-item label="故障类型" prop="faultTypes">
          <el-input v-model="form.faultTypes" placeholder="请输入故障类型，多个值请用逗号分隔" />
        </el-form-item>
        <el-form-item label="服务轮播图路径" prop="serviceCarouselImages">
          <image-upload v-model="form.serviceCarouselImages" />
        </el-form-item>
        <el-form-item label="服务详情图路径" prop="serviceDetailImage">
          <image-upload v-model="form.serviceDetailImage" />
        </el-form-item>
        <el-form-item label="上门费用" prop="visitFee">
          <el-input v-model="form.visitFee" placeholder="请输入上门费用" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDetail, getDetail, delDetail, addDetail, updateDetail } from "@/api/service/detail";
import { all } from "@/api/service/item";

export default {
  name: "Detail",
  data() {
    return {
      serviceItems: [], // 添加服务项目列表
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务详情表格数据
      detailList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        serviceItemId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        serviceItemId: [
          { required: true, message: "服务项目名不能为空", trigger: "blur" }
        ],
        serviceOptions: [
          { required: true, message: "服务选项不能为空", trigger: "blur" }
        ],
        serviceFeatures: [
          { required: true, message: "服务特点不能为空", trigger: "blur" }
        ],
        faultTypes: [
          { required: true, message: "故障类型不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
    this.getServiceItems(); // 获取服务项目列表
  },
  methods: {
    getServiceItems() {
      all().then(response => {
        this.serviceItems = response.data; // 假设返回的数据在 response.data 中
      });
    },
    parseJson(jsonString) {
      try {
        return JSON.parse(jsonString);
      } catch (error) {
        console.error('Invalid JSON string:', jsonString);
        return [];
      }
    },
    /** 查询服务详情列表 */
    getList() {
      this.loading = true;
      listDetail(this.queryParams).then(response => {
        this.detailList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        serviceItemId: null,
        serviceOptions: null,
        serviceFeatures: null,
        faultTypes: null,
        serviceCarouselImages: null,
        serviceDetailImage: null,
        visitFee: null,
        createTime: null,
        updateTime: null,
        isDeleted: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加服务详情";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDetail(id).then(response => {
        this.form = response.data;

        // 将 JSON 数组字符串转换为逗号分隔的字符串
        if (this.form.serviceOptions) {
          this.form.serviceOptions = this.parseJson(this.form.serviceOptions).join(', ');
        }
        if (this.form.serviceFeatures) {
          this.form.serviceFeatures = this.parseJson(this.form.serviceFeatures).join(', ');
        }
        if (this.form.faultTypes) {
          this.form.faultTypes = this.parseJson(this.form.faultTypes).join(', ');
        }

        this.open = true;
        this.title = "修改服务详情";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 将填入的多项值转换为 JSON 数组字符串
          this.form.serviceOptions = JSON.stringify(this.form.serviceOptions.split(',').map(item => item.trim()));
          this.form.serviceFeatures = JSON.stringify(this.form.serviceFeatures.split(',').map(item => item.trim()));
          this.form.faultTypes = JSON.stringify(this.form.faultTypes.split(',').map(item => item.trim()));

          if (this.form.id != null) {
            updateDetail(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDetail(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除服务详情编号为"' + ids + '"的数据项？').then(function () {
        return delDetail(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    }
  }
};
</script>
